package com.baor.seacurity;

import com.baor.domain.AdminVo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class JwtConfig {

    @Value("${config.jwt.secret}")
    private String secret;

    @Value("${config.jwt.expire}")
    private long expire;

    @Value("${config.jwt.header}")
    private String header;

    // create token
    public String createToken(AdminVo vo) {
        Date nowDate = new Date();
        Date expireDate = new Date(nowDate.getTime() + expire * 1000);
        Map<String, Object> claims = new HashMap<>();
        return Jwts.builder()
                .setClaims(claims)
                .setHeaderParam("typ", "JWT")
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)
                .setSubject(vo.getAdminAccount())
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    // get claims
    public Claims getClaims(String authorization){
        try{
            return Jwts.parser().setSigningKey(secret).parseClaimsJws(authorization).getBody();
        }catch (Exception e){
            return null;
        }
    }
    public String getSubject(String authorization){
        return getClaims(authorization).getSubject();
    }

    public boolean isTokenExpired(String authorization){
        if(getClaims(authorization) == null){
            return true;
        }
        Date tokenDate = getClaims(authorization).getExpiration();
        return tokenDate.before(new Date());
    }
}
